package top.wuyang.study.javaexam;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class TbGoodsDAO {

    public static int insert(TbGoods tbGoods) throws Exception {
        Connection conn = DBHelper.getConnection();
        String sql = "insert into tb_goods(typeinfo,gname,price,amount) values(?,?,?,?)";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1, tbGoods.getTypeinfo());
        ps.setString(2, tbGoods.getGname());
        ps.setInt(3, tbGoods.getPrice());
        ps.setInt(4, tbGoods.getAmount());
        int i = ps.executeUpdate();
        conn.close();
        return i;

    }

    public static List<TbGoods> query() throws Exception {
        List<TbGoods> list = new ArrayList<>();
        Connection conn = DBHelper.getConnection();
        String sql = "select * from tb_goods";
        PreparedStatement ps = conn.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            TbGoods tbGoods = new TbGoods();
            tbGoods.setId(rs.getInt("id"));
            tbGoods.setTypeinfo(rs.getString("typeinfo"));
            tbGoods.setGname(rs.getString("gname"));
            tbGoods.setPrice(rs.getInt("price"));
            tbGoods.setAmount(rs.getInt("amount"));
            list.add(tbGoods);


        }
        conn.close();
        return list;

    }


    public static int delete(Integer id) throws Exception{

        Connection conn = DBHelper.getConnection();
        String sql = "delete from tb_goods where id = ?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setInt(1,id);
        int i = ps.executeUpdate();
        conn.close();
        return i;



    }





}
